package com.lookup.api.verticle;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.lookup.api.guice.DBModule;
import com.lookup.api.guice.HandlerModule;
import com.lookup.api.guice.LoggerModule;
import com.lookup.api.guice.ServiceModule;
import com.lookup.api.handler.http.AliveHandler;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.core.http.HttpServer;
import io.vertx.rxjava.ext.web.Router;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.schedulers.Schedulers;


public class HttpWorkerVerticle extends AbstractVerticle {

    private Logger logger = LoggerFactory.getLogger("init.server" + HttpWorkerVerticle.class.getName());

    @Override
    public void start() throws Exception {

        int port = 1234;
        Injector injector = Guice.createInjector(new LoggerModule(), new HandlerModule(),
                new ServiceModule(), new DBModule());
        //注册路由
        Router router = Router.router(vertx);
        router.get("/alive").handler(injector.getInstance(AliveHandler.class));
        // 配置http服务基础参数
        HttpServerOptions options = new HttpServerOptions();
        options.setPort(port);
        options.setHost("localhost");
        options.setReuseAddress(true);
        options.setTcpKeepAlive(true);
        HttpServer server = vertx.createHttpServer(options);
        server.requestHandler(router::accept).rxListen().subscribeOn(Schedulers.io())
                   .subscribe(context -> {
                    logger.info("server init port: " + port);
                    // eventBus 向其他 Verticle发送消息
                    // String verticleAddress  ="news.uk.sport";
                    // getVertx().eventBus().send(verticleAddress,"server init  ok");
                    logger.info("start.server.complete");
                    },
                    failure -> {
                        logger.info("server init fail");
                    });
    }
}
